package com.ecreditpal.toto.util;

import lombok.extern.slf4j.Slf4j;
import lombok.extern.slf4j.XSlf4j;
import org.apache.commons.configuration2.CompositeConfiguration;
import org.apache.commons.configuration2.Configuration;
import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.SystemConfiguration;
import org.apache.commons.configuration2.ex.ConfigurationException;

import java.io.File;
import java.io.FileReader;
import java.io.IOException;

/**
 * @author lifeng
 * @version 1.0 on 2018/4/21.
 */
@Slf4j
public class ConfigurationManager {
    private static final CompositeConfiguration cc = new CompositeConfiguration();

    static {
        try {
            loadConfig();
        } catch (Exception e) {
//            log.info("can not parse the configuration",e);
        }
    }

    private ConfigurationManager() {
    }

    public static Configuration getConfiguration() {
        return cc;
    }

    private static void loadConfig() throws IOException, ConfigurationException {
        log.info("start loading config");
        cc.addConfiguration(new SystemConfiguration());
        //判断是否为本地
        String productConfigDir = cc.getString("config.dir");
        String env = cc.getString("spring.profiles.active");
        String propertiesPath;
        PropertiesConfiguration conf = null;
        if (productConfigDir == null) {
            //从本地获取配置文件
            propertiesPath = "target/classes/application.properties";
            conf = new PropertiesConfiguration();
            conf.read(new FileReader(propertiesPath));
            File file = new File("src/main/resources");
            listFile(file, conf);
        } else {
            //从服务器的目录获取配置文件
            propertiesPath = productConfigDir+ "/application-"+env+".properties";
            File file = new File(propertiesPath);
            if (file.exists()) {
                conf = new PropertiesConfiguration();
                conf.read(new FileReader(file));
                file = new File(productConfigDir);
                listFile(file, conf);
            }
        }
        cc.addConfiguration(conf);
    }


    private static void listFile(File file, PropertiesConfiguration conf) {
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File f : files) {
                    listFile(f, conf);
                }
            }
        } else {
            conf.addProperty(file.getName(), file.getAbsolutePath());
        }
    }


}
